package com.dex4d.utils;

import android.text.InputFilter;
import android.text.Spanned;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DecimalInputFilter implements InputFilter {

    private  final String REGEX_INPUT_LIMIT = "[0-9.]";
    private static final int MAX_INPUT = 1000000000;
    private static final int GET_POINT_LOWEST_LENGTH = 8;
    private static final int POINT_OFFSET = 7;

    @Override
    public CharSequence filter(CharSequence source,
                               int start,
                               int end,
                               Spanned dest,
                               int dstart,
                               int dend) {


        // 限制1：只能输入数字和"."
        Pattern p = Pattern.compile(REGEX_INPUT_LIMIT);
        Matcher matcher = p.matcher(source.toString());
        if (!matcher.find()){
            return "";
        }

        // 限制2：首位不能输入"."
        if (dend == 0 && source.toString().equals(".")){
            return "";                  // 这里如果返回null无效
        }

        // 限制3：如果已经有“.”，则不能再输入“.”
        if (dest.toString().contains(".") && source.equals(".")){
            return "";
        }

        // 限制4：如果上一个字符为0，则下一位只能输入点
        if (dest.toString().equals("0") && !source.toString().equals(".")){
            return "";
        }

        // 限制5：如果大于MAX_INPUT，则不能输入
        double inputNum = Double.parseDouble(dest.toString()+source);
        if (inputNum > MAX_INPUT){
            return "";
        }

        // 限制6：如果上次上两位数前是".",则不能再输入(0.01长度为4)
        if (dest.length() >= GET_POINT_LOWEST_LENGTH
                && dest.charAt(dest.length()-POINT_OFFSET) == '.'){
            return "";
        }

        return null;
    }

}